<?php

namespace App\Exports;

use App\Models\Balance;
use Carbon\Carbon;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromCollection;
// use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

class BalancesExport implements FromCollection, WithHeadings, WithMapping
{
  public function collection()
  {
    $req = request();
    return Balance::when($req->has('type'), function ($q) use ($req) {
      $q->where('type', $req->type);
    })->when($req->has('created_at'), function ($q) use ($req) {
      [$start, $end] = explode(',', $req->created_at);
      $start = Carbon::create($start)->format('Y-m-d');
      $end = Carbon::create($end)->format('Y-m-d');
      $q->whereBetween('created_at', [$start, $end]);
    })
      ->where('user_id', sellerId())
      ->latest()
      ->get();
  }

  public function headings(): array
  {
    return [
      'ID',
      '帐变类型',
      '变化值',
      '变化前',
      '变化后',
      '创建时间',
      '订单号',
    ];
  }

  public function map($balance): array
  {
    return [
      $balance->id,
      $balance->type,
      $balance->value,
      $balance->b4,
      $balance->after,
      $balance->created_at->format('Y-m-d H:i'),
      $balance->order_id . ' '
    ];
  }

  // public function columnFormats(): array
  // {
  //   return [
  //     'G' => NumberFormat::FORMAT_TEXT,
  //   ];
  // }
}
